<?php
// Do not hide errors.
error_reporting (E_ALL);

// Define system consts.
define('SITE_DIR',			dirname(dirname(__FILE__)).'/');
define('TEMP_DIR',			SITE_DIR."tmp/");
define('ENGINE_DIR',		SITE_DIR."engine/");
define('ENGINE_NAME',		'Cosmiqum');
define('ENGINE_VERSION',	'0.3');

// Check temp directory to exists and to be writeable.
if (!file_exists(TEMP_DIR))
{
	die("Temp directory does not exists at ".TEMP_DIR);
}

if (!is_writeable(TEMP_DIR))
{
	die("Temp direcoty is not writeable. Chmod ".TEMP_DIR." to 777");
}

if (!function_exists('xml_parser_create'))
{
	die("No XML support!");
}

// Load timer.
include_once ENGINE_DIR.'includes/timer.class.php';
$oTimer = new CTimer;
$oTimer->Start();

// Register first eventt
$oTimer->RegisterEvent('Timer started');

// Load error handler.
include_once ENGINE_DIR.'includes/errors.class.php';
$oErrors = new CErrors;
//set_error_handler(array($oErrors, 'Handler'));
$oTimer->RegisterEvent('Starting capture errors');

// Load functions.
include_once ENGINE_DIR.'includes/functions.php';

// Remove all slashes
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
	$_REQUEST	= RemoveSlashes($_REQUEST);
	$_GET		= RemoveSlashes($_GET);
	$_POST		= RemoveSlashes($_POST);
	$_COOKIE	= RemoveSlashes($_COOKIE);
}

// Backup not filtered input variables
$_REQUEST_REAL	= $_REQUEST;
$_GET_REAL	= $_GET;
$_POST_REAL	= $_POST;
$_COOKIE_REAL	= $_COOKIE;

// Filter all input variables to avoid XSS
$_REQUEST	= FilterHtmlSpecialChars($_REQUEST);
$_GET		= FilterHtmlSpecialChars($_GET);
$_POST		= FilterHtmlSpecialChars($_POST);
$_COOKIE	= FilterHtmlSpecialChars($_COOKIE);

// Set private cache control
header('Cache-control: private');

// Get alias for requested host to load specific config for this host.
// Get hostname
$g_sHost = $_SERVER['SERVER_NAME'];

// Get server protocol
if (strpos(strtoupper($_SERVER['SERVER_PROTOCOL']), 'HTTPS')>0)
{
	$g_sProtocol = 'https';
}
else
{
	$g_sProtocol = 'http';
}

// Get server port
$g_sPort = $_SERVER['SERVER_PORT'];

// Define home URL
if ($g_sPort == 80)
{
	define('HOME_URL',	"$g_sProtocol://$g_sHost");
}
else
{
	define('HOME_URL',	"$g_sProtocol://$g_sHost:$g_sPort");
}

define('SELF', $_SERVER['PHP_SELF']);

// Get referer
if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'])
{
	define('REFERER', $_SERVER['HTTP_REFERER']);
}
else
{
	define('REFERER', '');
}

// Default host alias
$g_sHostAlias = 'default';

$oTimer->RegisterEvent('Trying to define host alias');
// Check if config file with hosts list is exists
if (file_exists(ENGINE_DIR.'config/hosts.txt'))
{
	$sHosts = file_get_contents(ENGINE_DIR.'config/hosts.txt');
	$aHosts = json_decode($sHosts, true);
	if (count($aHosts)>0)
	{
		foreach ($aHosts as $aHost)
		{
			if (!$aHost['alias'])
			{
				continue;
			}

			$sAlias = $aHost['alias'];
			$iMatches = 0;

			foreach ($aHost['params'] as $sKey => $sValue)
			{
				if (isset($_SERVER[$sKey]) && $_SERVER[$sKey])
				{
					if ($_SERVER[$sKey] == $sValue)
					{
						$iMatches++;
					}
					else if (preg_match("/%(.*)%[a-z]*/", $sValue))
					{
						if (preg_match($sValue, $_SERVER[$sKey]))
						{
							$iMatches++;
						}
					}
				}
			}

			if ($iMatches == count($aHost['params'])-1)
			{
				if (file_exists(ENGINE_DIR."config/$sAlias/config.txt") &&
					file_exists(ENGINE_DIR."config/$sAlias/plugins.txt") &&
					file_exists(ENGINE_DIR."config/$sAlias/plugins.lst") &&
					is_dir(ENGINE_DIR.'config/plugins/'))
				{
					$g_sHostAlias = $sAlias;
					break;
				}
			}
		}		
	}
}

// Define const for configs directory
define('CONF_DIR', ENGINE_DIR."config/$g_sHostAlias/");
$oTimer->RegisterEvent('Defined host alias: '.$g_sHostAlias);

// Parse config
$sConfig = file_get_contents(CONF_DIR.'config.txt');
$g_aConfig = json_decode($sConfig, true);
if (count($g_aConfig)>0)
{
	$oTimer->RegisterEvent('Config file is loaded');
}
else
{
	die('Error parsing config file!');
}
	

// Define language
$g_sLanguage = $g_aConfig['language'];
if (isset($_REQUEST['engine_language']))
{
	$sLangReq = str_replace(array("/",".."), "", $_REQUEST['engine_language']);
	if (file_exists(ENGINE_DIR."languages/$sLangReq.xml"))
	{
		$g_sLanguage = $sLangReq;		
	}
}

// Load plugins class
include_once ENGINE_DIR.'includes/plugins.class.php';
$P = new CPlugin;
$oPlugins = new CPlugins;

$oPlugins->LoadLang();
$oTimer->RegisterEvent(sprintf($g_aLang['core']['log']['lang_loaded'], $g_aLang['core']['caption_native']));
$oTimer->RegisterEvent($g_aLang['core']['log']['core_included']);

foreach ($oPlugins->GetList() as $aPlugin)
{
	if (!file_exists(ENGINE_DIR.'plugins/'.$aPlugin['Id'].'/')
		|| !file_exists(ENGINE_DIR.'plugins/'.$aPlugin['Id'].'/'.$aPlugin['Id'].'.php'))
	{
		$oTimer->RegisterEvent(
			sprintf($g_aLang['core']['log']['plugin_cant_load'], $aPlugin['Id']) .
			$g_aLang['core']['log']['plugin_no_file']
		);	
		continue;
	}
	
	if (class_exists("C".$aPlugin['Class']."Plugin"))
	{
		$oTimer->RegisterEvent(
			sprintf($g_aLang['core']['log']['plugin_cant_load'], $aPlugin['Id']) .
			sprintf($g_aLang['core']['log']['plugin_class_exists'], $aPlugin['Id'])
		);
		continue;
	}	

	if (isset($aPlugin['Depends']) && $aPlugin['Depends'])
	{
		foreach ($aPlugin['Depends'] as $sDep)
		{
			$b_Yes = false;
			foreach ($oPlugins->aList as $key => $value)
			{
				if (isset($value['Class']) && $value['Class']==$sDep)
				{
					$b_Yes = true;
				}
				
			}
			
			if (!$b_Yes)
			{
				$oTimer->RegisterEvent(
					sprintf($g_aLang['core']['log']['plugin_cant_load'], $aPlugin['Id']) .
					sprintf($g_aLang['core']['log']['plugin_dep_missing'], $sDep)
				);
				continue 2;
			}
		}
	}

	include ENGINE_DIR.'plugins/'.$aPlugin['Id'].'/'.$aPlugin['Id'].'.php';

	if (!class_exists("C".$aPlugin['Class']."Plugin"))
	{
		$oTimer->RegisterEvent(
			sprintf($g_aLang['core']['log']['plugin_cant_load'], $aPlugin['Id']) .
			$g_aLang['core']['log']['plugin_no_init']
		);	
		continue;
	}

	eval("\$P->".$aPlugin['Class']." = new C".$aPlugin['Class']."Plugin;");
	eval("\$bResult = \$P->".$aPlugin['Class']."->Init();");
	
	if (!$bResult)
	{
		$oTimer->RegisterEvent(
			sprintf($g_aLang['core']['log']['plugin_cant_load'], $aPlugin['Id']) .
			$g_aLang['core']['log']['plugin_init_false']
		);	
		continue;
	}

	$oPlugins->aListActive[$aPlugin['Id']] = true;
	$oTimer->RegisterEvent(sprintf($g_aLang['core']['log']['plugin_loaded'], $aPlugin['Id']));
}

$oPlugins->ExecuteEvent('PluginsLoaded');
$oTimer->RegisterEvent($g_aLang['core']['log']['core_loaded']);
